import os
import time

import pandas as pd
import requests

#视频id
video_id_arr = []
video_id_demo = 7367499739987791154

#获取评论的条数
count = 50

# 请求地址
url = 'https://www.douyin.com/aweme/v1/web/comment/list/'

# 请求头
h1 = {
    'accept': 'application/json, text/plain, */*',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'cookie': 'LOGIN_STATUS=1; store-region=cn-sc; store-region-src=uid; my_rd=2; xgplayer_device_id=63538777348; __live_version__=%221.1.1.5086%22; live_use_vvc=%22false%22; __ac_signature=_02B4Z6wo00f01amgWpgAAIDAuf6.oSLP.mmpgF4AAA8jq1ygtMwIJW0H4JqwP8eDRhgwk6jrnQ2iwYwhPHcsn9W4O6VRHko4uZyc.AGy3LUvG462oFZVZtl2GECdOLtTwcvn07WlgT4o5.JN91; xgplayer_user_id=291379087538; d_ticket=59e249d91121d58b71aaab1b6efa6bd1cd632; n_mh=tUbVBq7lfkY-CrNICBn4eTBXDweUbH0LvOGvXsXISx0; passport_csrf_token=fa0077a193a25c0eced725e7c217f2ee; passport_csrf_token_default=fa0077a193a25c0eced725e7c217f2ee; douyin.com; device_web_cpu_core=32; device_web_memory_size=8; architecture=amd64; dy_swidth=1920; dy_sheight=1080; stream_recommend_feed_params=%22%7B%5C%22cookie_enabled%5C%22%3Atrue%2C%5C%22screen_width%5C%22%3A1920%2C%5C%22screen_height%5C%22%3A1080%2C%5C%22browser_online%5C%22%3Atrue%2C%5C%22cpu_core_num%5C%22%3A32%2C%5C%22device_memory%5C%22%3A8%2C%5C%22downlink%5C%22%3A10%2C%5C%22effective_type%5C%22%3A%5C%224g%5C%22%2C%5C%22round_trip_time%5C%22%3A50%7D%22; csrf_session_id=70400c63d6126f675078dca9ca62f363; FORCE_LOGIN=%7B%22videoConsumedRemainSeconds%22%3A180%7D; volume_info=%7B%22isUserMute%22%3Afalse%2C%22isMute%22%3Atrue%2C%22volume%22%3A0.991%7D; strategyABtestKey=%221715147429.724%22; bd_ticket_guard_client_web_domain=2; passport_assist_user=CkEAxq2-ps5ynnRNnclijyshJh_Vg__QWOfpPGBdnIajXOtvxCqNmp1eklwgG412MpM70Fjb2jkdVKVvAHdxcX51cxpKCjwNAn5arzStUE6yOhVR3jyCQ03-F1LXa2LYLC7f_UXBJeTYsu2R26G9sZJC4B35n85DZXY5_xMT1vml7ugQq93QDRiJr9ZUIAEiAQNeN-Xr; sso_uid_tt=87c0e74a30d890d4b98524d73a13bfe2; sso_uid_tt_ss=87c0e74a30d890d4b98524d73a13bfe2; toutiao_sso_user=c85c3098a241d168b19fe45b21564c02; toutiao_sso_user_ss=c85c3098a241d168b19fe45b21564c02; sid_ucp_sso_v1=1.0.0-KDM4MDA0ZTZmYWIyYjQ2YjE1ZWI3MTg0ZmQ5ZTVhODkwNDk5MGIyOTkKHwj-_cCe2Y3MBxDZpeyxBhjvMSAMMPGA5YYGOAZA9AcaAmhsIiBjODVjMzA5OGEyNDFkMTY4YjE5ZmU0NWIyMTU2NGMwMg; ssid_ucp_sso_v1=1.0.0-KDM4MDA0ZTZmYWIyYjQ2YjE1ZWI3MTg0ZmQ5ZTVhODkwNDk5MGIyOTkKHwj-_cCe2Y3MBxDZpeyxBhjvMSAMMPGA5YYGOAZA9AcaAmhsIiBjODVjMzA5OGEyNDFkMTY4YjE5ZmU0NWIyMTU2NGMwMg; passport_auth_status=56e6820133e226cefb748196d2e42e0e%2C; passport_auth_status_ss=56e6820133e226cefb748196d2e42e0e%2C; uid_tt=a8e0f5fe1c49f56a77405a603df9b8cc; uid_tt_ss=a8e0f5fe1c49f56a77405a603df9b8cc; sid_tt=b23a0f63304f14b94ae5a36102011e47; sessionid=b23a0f63304f14b94ae5a36102011e47; sessionid_ss=b23a0f63304f14b94ae5a36102011e47; s_v_web_id=verify_lvxej01o_dUpSlGV2_VUdp_45Ss_9kBO_IKXdHUcm14Zx; _bd_ticket_crypt_doamin=2; _bd_ticket_crypt_cookie=7da5989eccda82feff45b1b3144bcfff; __security_server_data_status=1; sid_guard=b23a0f63304f14b94ae5a36102011e47%7C1715147671%7C5183813%7CSun%2C+07-Jul-2024+05%3A51%3A24+GMT; sid_ucp_v1=1.0.0-KDYxMGI1Mzg4N2FmOWNjYjZjNGIzNTk1ZGY4MDJiNGQxNWJmMDc2N2MKGwj-_cCe2Y3MBxCXp-yxBhjvMSAMOAZA9AdIBBoCaGwiIGIyM2EwZjYzMzA0ZjE0Yjk0YWU1YTM2MTAyMDExZTQ3; ssid_ucp_v1=1.0.0-KDYxMGI1Mzg4N2FmOWNjYjZjNGIzNTk1ZGY4MDJiNGQxNWJmMDc2N2MKGwj-_cCe2Y3MBxCXp-yxBhjvMSAMOAZA9AdIBBoCaGwiIGIyM2EwZjYzMzA0ZjE0Yjk0YWU1YTM2MTAyMDExZTQ3; theme=%22dark%22; FOLLOW_LIVE_POINT_INFO=%22MS4wLjABAAAAEZ7KRn9fHUzJ_bB888WmlIxSYpCUOKiDa5F974fC6Pdj9E0vVh6R6MeKOROzAg7N%2F1715184000000%2F0%2F0%2F1715148359165%22; publish_badge_show_info=%221%2C0%2C1%2C1715147651854%22; ttwid=1%7Cq-P4iEEa8gs1xv-euUBDZGZN8HUYPGjHTYD7NnMQkTE%7C1715147791%7C9ac59607090cad32ca0344a344a3dd64cb1ff661df0e00f8304bb64e281b5d2c; FOLLOW_NUMBER_YELLOW_POINT_INFO=%22MS4wLjABAAAAEZ7KRn9fHUzJ_bB888WmlIxSYpCUOKiDa5F974fC6Pdj9E0vVh6R6MeKOROzAg7N%2F1715184000000%2F1715147777713%2F1715147759166%2F0%22; download_guide=%223%2F20240508%2F0%22; IsDouyinActive=true; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCT3dxVU9VZGtXSndPZVJFQTlic3FJVEtXM0F1clZhVHU1QlZqbVl3ZXd4Q1AvYUlHZTRlQ0FuQ1FxSzNROVV2QldaRXBPRzV5dzZWU3cyWHN4V0o4Nnc9IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoxfQ%3D%3D; passport_fe_beating_status=true; home_can_add_dy_2_desktop=%221%22; odin_tt=23b59cee48d5ec53759e5cf3dadf90a501b6afaf20a7a552940dae86f188d7dda92e213637ec1664d6756f89981c1db9; pwa2=%220%7C0%7C3%7C1%22; WallpaperGuide=%7B%22showTime%22%3A1715147762399%2C%22closeTime%22%3A0%2C%22showCount%22%3A1%2C%22cursor1%22%3A19%2C%22cursor2%22%3A0%2C%22hoverTime%22%3A1715147776243%7D; stream_player_status_params=%22%7B%5C%22is_auto_play%5C%22%3A0%2C%5C%22is_full_screen%5C%22%3A0%2C%5C%22is_full_webscreen%5C%22%3A0%2C%5C%22is_mute%5C%22%3A1%2C%5C%22is_speed%5C%22%3A1%2C%5C%22is_visible%5C%22%3A1%7D%22; xg_device_score=8.132128945374028; msToken=L8mFqlwNyXPOoShMf4CC_2sRtA_a4iQo1MbDLWdLjaCDaYEIfTgbVW4e_b3Y_pGclp3ORbgdSyCXx4oU4U4AFDL0eU9xf0dOkjcn3JURkKWGtCpMNOMfHrTKroXU',
    'referer': 'https://www.douyin.com/',
    'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Microsoft Edge";v="122"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0',
}

ip_list = []  # ip属地
text_list = []  # 评论内容
create_time_list = []  # 评论时间
user_name_list = []  # 评论者昵称
user_unique_id_list = []  # 评论者抖音号
like_count_list = []  # 点赞数


def main():
    #应该写一个异常处理免得爬一半被封了
    file_len = 10000
    episoda=int(file_len / 50)
    print("episoda_total：",episoda)
    for i in range(episoda):
        print("episoda：",i)
        # 请求参数
        params = {
            'device_platform': 'webapp',
            'aid': 6383,
            'channel': 'channel_pc_web',
            'aweme_id': video_id_demo,  # 视频id
            'cursor': i*count,
            'count': count,
            'item_type': 0,
            'insert_ids': '',
            'rcFT': '',
            'pc_client_type': 1,
            'version_code': '170400',
            'version_name': '17.4.0',
            'cookie_enabled': 'true',
            'screen_width': 1440,
            'screen_height': 900,
            'browser_language': 'zh-CN',
            'browser_platform': 'MacIntel',
            'browser_name': 'Chrome',
            'browser_version': '109.0.0.0',
            'browser_online': 'true',
            'engine_name': 'Blink',
            'engine_version': '109.0.0.0',
            'os_name': 'Mac OS',
            'os_version': '10.15.7',
            'cpu_core_num': 4,
            'device_memory': 8,
            'platform': 'PC',
            'downlink': 1.5,
            'effective_type': '4g',
            'round_trip_time': 50,
            'webid': 7335665906297947660,
            'msToken': 'LZ3nJ12qCwmFPM1NgmgYAz73RHVG_5ytxc_EMHr_3Mnc9CxfayXlm2kbvRaaisoAdLjRVPdLx5UDrc0snb5UDyQVRdGpd3qHgk64gLh6Tb6lR16WG7VHZQ==',
        }
        # 发送请求
        r = requests.get(url, headers=h1, params=params)
        # 转json格式
        json_data = r.json()
        comment_len = len(list(json_data['comments']))

        if comment_len != 0:
            # 获取得到的评论的条数
            for i in range(int(comment_len)):
                ip_list.append(json_data['comments'][i]['ip_label'])
                text_list.append(json_data['comments'][i]['text'])
                create_time_list.append(json_data['comments'][i]['create_time'])
                user_name_list.append(json_data['comments'][i]['user']['nickname'])
                like_count_list.append(json_data['comments'][i]['digg_count'])
            if comment_len != count:
                return 1


main()
print("准备写入，请稍后")
# 保存数据到DF
df = pd.DataFrame(
    {
        '目标链接': 'https://www.douyin.com/video/' + str(video_id_demo),
        '评论者昵称': user_name_list,
        '评论时间': create_time_list,
        '评论IP属地': ip_list,
        '评论点赞数': like_count_list,
        '评论内容': text_list,
    }
)
result_file = "csv_dir/7367499739987791154.csv"

df.to_csv(result_file, mode='a+', index=False, encoding='utf_8_sig')